﻿using Microsoft.Extensions.Logging;
using ValidationException = MeetingRoomBooking.Application.Common.Exceptions.ValidationException;
namespace MeetingRoomBooking.Application.Common.Behaviours;
public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : notnull
{
    private readonly ILogger<TRequest> _logger;

    public UnhandledExceptionBehaviour(ILogger<TRequest> logger)
    {
        _logger = logger;
    }

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        try
        {
            return await next();
        }
        catch (Exception ex)
        {
            var requestName = typeof(TRequest).Name;

            if (ex is ValidationException validationException)
            {
                _logger.LogWarning("Validation failed for request {Name}: {Errors}", requestName, validationException.Errors);
            }
            else
            {
                _logger.LogError(ex, "MeetingRoomBooking Request: Unhandled Exception for Request {Name} {@Request}", requestName, request);
            }

            throw;
        }
    }
}
